import moment from 'moment';
import _ from 'lodash';
import { ToFixed, TIME_ENUM } from '../../tool';
import { IFixedPredictivePowerLine } from '../../type';
import { getCssVariableValue } from '@/utils/utils';

const POINTER_NUM = TIME_ENUM(96);

const enumerateDaysBetweenDates = (startDate, endDate) => {
  let daysList = [];
  const start = moment(startDate);
  const end = moment(endDate);
  const day = end.diff(start, 'day');
  daysList.push(start.format('YYYY-MM-DD'));
  for (let i = 1; i <= day; i++) {
    daysList.push(start.add(1, 'day').format('YYYY-MM-DD'));
  }
  return daysList;
};

// 系列相关
export function getSeri({ type, name, color, lineStyle, ...others }) {
  let config = {
    type,
    name,
    itemStyle: { color },
  };
  if (type === 'line') {
    config = {
      ...config,
      symbol: 'none',
      lineStyle: lineStyle || { width: 1 },
    };
  } else if (type === 'bar') {
    config = {
      barMaxWidth: 8,
      ...config,
    };
  }
  return {
    ...config,
    ...others,
  };
}

// 基础配置
export const getOptions = ({
  titleText,
  XAXIS,
  xAxis,
  tooltip,
  yAxis,
  grid,
  legendData,
  dataZoom,
  ...rest
}) => {
  return {
    title: {
      text: titleText,
      show: true,
      top: 8,
      left: -4,
      textStyle: {
        fontSize: 14,
        lineHeight: 14,
        color: getCssVariableValue('--font'),
      },
    },
    grid: grid || {
      top: 16,
      left: 46,
      bottom: 110,
      right: 0,
    },
    tooltip: tooltip || {
      trigger: 'axis',
      padding: 12,
      axisPointer: {
        type: 'line',
        lineStyle: {
          color: '#A7A8A9',
          width: 1,
          type: 'solid',
        },
      },
      position: function (point, params, dom, rect, size) {
        let x = 0;
        let y = 0;
        const pointX = point[0];
        const pointY = point[1];
        const boxWidth = size.contentSize[0];
        const boxHeight = size.contentSize[1];
        if (boxWidth > pointX) {
          x = pointX + 15;
        } else {
          x = pointX - boxWidth - 15;
        }
        if (boxHeight > pointY) {
          y = 5;
        } else {
          y = pointY - boxHeight;
        }
        return [x, y];
      },
      show: true,
      backgroundColor: '#161A1D',
      borderColor: '#161A1D',
      borderWidth: 1,
      textStyle: {
        color: '#A7A8A9',
        fontFamily: 'PingFang SC',
        fontStyle: 'none',
        fontSize: 12,
      },
    },
    legend: {
      right: 'center',
      top: 'bottom',
      padding: [16, 0, 0, 0],
      itemGap: 20,
      itemWidth: 15,
      itemHeight: 8,
      textStyle: {
        color: getCssVariableValue('--chart-legend-color'),
      },
      show: true,
      data: legendData,
      inactiveColor: '#545454',
      inactiveBorderColor: '#545454',
      inactiveBorderWidth: 'inherit',
    },
    xAxis: xAxis || {
      type: 'category',
      boundaryGap: false,
      data: XAXIS.map((v) => v || ''),
      splitNumber: Math.random(),
      axisPointer: {
        type: 'line',
        lineStyle: {
          color: getCssVariableValue('--bd-a50'),
        },
      },
      axisLine: {
        show: true,
        onZero: true,
        lineStyle: {
          type: 'solid',
          color: getCssVariableValue('--chart-x-line'),
        },
      },
      axisTick: {
        alignWithLabel: true,
        lineStyle: {
          color: getCssVariableValue('--chart-x-line'),
        },
      },
      axisLabel: {
        color: getCssVariableValue('--chart-font-color'),
        fontStyle: 'DIN-Light',
        fontSize: 12,
        lineHeight: 12,
        margin: 9,
      },
    },
    yAxis: yAxis || {
      type: 'value',
      axisLine: {
        show: false,
      },
      axisTick: {
        alignWithLabel: true,
        length: 4,
        lineStyle: {
          color: getCssVariableValue('--chart-y-line'),
        },
      },
      axisLabel: {
        color: getCssVariableValue('--chart-font-color'),
        fontStyle: 'DIN-Light',
        fontSize: 12,
        margin: 8,
        height: 12,
      },
      splitLine: {
        show: true,
        lineStyle: {
          type: 'solid',
          color: getCssVariableValue('--chart-y-line'),
        },
      },
    },
    dataZoom: dataZoom || [
      {
        type: 'slider',
        start: 0,
        end: 100,
        bottom: 28,
        height: 20,
        backgroundColor: '#2B2E32',
        dataBackground: {
          lineStyle: {
            color: '#4E5154',
          },
          areaStyle: {
            color: '#2B2E32',
          },
        },
        selectedDataBackground: {
          lineStyle: {
            color: '#4E5154',
          },
          areaStyle: {
            color: '#646769',
            opacity: 0.2,
          },
        },
        borderColor: '#2B2E32',
        handleStyle: {
          color: '#646769',
        },
        moveHandleStyle: {
          color: '#EFF2F9',
        },
        brushSelect: false,
        showDetail: false,
      },
    ],
    ...rest,
  };
};

const formatSpecialTooltipTwo = (val) => {
  let _val = [
    ...val.filter((item) => {
      return item.seriesName !== IFixedPredictivePowerLine.AFFECT_CAPACITY;
    }),
    ...val.filter((item) => {
      return item.seriesName === IFixedPredictivePowerLine.AFFECT_CAPACITY;
    }),
  ];
  let str = `<div style='background: #161A1D;min-width:120px;display: inline-block;font-size: 12px; max-height: 400px;overflow-y: auto;'><div style='display: flex;align-items: center;color: #7A7D7F;margin-bottom: 4px'>
  <span style='margin-left: 4px'>${_val[0].name}</span>
</div>`;
  _val.map((item, index) => {
    if (index === _val.length - 1) {
      str += `<div style="height:0; border-top:1px solid #4E5154; margin: 8px 0 8px 0;"></div>`;
    }
    str += `
    <div style='display: flex;justify-content: space-between;align-items: center;color: #A7A8A9;margin-bottom: ${
      index === val.length - 1 ? '0px' : '4px'
    }'>
      <div style='display: flex;justify-content: flex-start;align-items: center;margin-right:10px'>
        <span style='display:inline-block;width:10px;height:10px;border-radius:5px;background: ${
          item.color
        };margin-right: 4px'></span>
        <span>${item.seriesName}</span>
      </div>
      <span style='color: #A7A8A9; font-weight: 500'>${item.value ?? '-'}</span>
    </div>
  `;
  });
  str += `</div>`;
  return str;
};

// tooltip
function formatNomalTooltip(val) {
  let str = `<div style='background: #161A1D;min-width:120px;display: inline-block;font-size: 12px; max-height: 400px;overflow-y: auto;'><div style='display: flex;align-items: center;color: #7A7D7F;margin-bottom: 4px'>
  <span>${val[0]?.name}</span>
</div>`;
  val.map((item, index) => {
    str += `
        <div style='display: flex;justify-content: space-between;align-items: center;color: #A7A8A9;margin-bottom: ${
          index === val?.length - 1 ? '0px' : '4px'
        }'>
          <div style='display: flex;justify-content: flex-start;align-items: center;margin-right:10px'>
            <span style='display:inline-block;width:10px;height:10px;border-radius:5px;background: ${
              item?.color
            };margin-right: 4px'></span>
            <span>${item?.seriesName}</span>
          </div>
          <span style='color: #A7A8A9; font-weight: 500'>${item?.value ?? '-'}</span>
        </div>
      `;
  });
  str += `</div>`;
  return str;
}

// 功率预测评价
// 偏差指数
export function deviationIndex(data = []) {
  const grid = {
    top: 8,
    left: 46,
    bottom: 45,
    right: 0,
  };
  const COLORLIST = [
    '#FA752B',
    '#5E92F6',
    '#67DCAB',
    '#078588',
    '#64779B',
    '#76D4F9',
    '#EE8CB7',
    '#F4903D',
    '#9562BF',
    '#A6D547',
    '#F5BE15',
  ];
  const XAXIS = TIME_ENUM(24);
  const yAxis = [
    {
      type: 'value',
      name: ' ',
      axisLine: {
        show: false,
      },
      axisTick: {
        alignWithLabel: true,
        length: 4,
        lineStyle: {
          color: getCssVariableValue('--chart-y-line'),
        },
      },
      axisLabel: {
        color: getCssVariableValue('--chart-font-color'),
        fontStyle: 'DIN-Light',
        fontSize: 12,
        margin: 8,
        height: 12,
      },
      splitLine: {
        show: true,
        lineStyle: {
          type: 'solid',
          color: getCssVariableValue('--chart-y-line'),
        },
      },
    },
  ];
  const legendData = data?.map((item, index) => {
    return {
      name: item?.dataSourceName,
      itemStyle: {
        opacity: 1,
        borderWidth: 1,
        // borderColor: COLORLIST[index],
        // color: '#222629',
      },
    };
  });
  const series = data?.map((item, index) => {
    return getSeri({
      type: 'line',
      name: item?.dataSourceName,
      color: COLORLIST[index],
      data: item?.values.map((i) => (i || i === 0 ? ToFixed(i, 3) : '-')),
    });
  });
  const option = getOptions({
    titleText: '',
    XAXIS,
    grid,
    yAxis,
    dataZoom: [],
    legendData,
  });
  return {
    ...option,
    tooltip: {
      ...option.tooltip,
      formatter: (e) => formatNomalTooltip(e),
      axisPointer: {
        type: 'line',
        lineStyle: {
          color: '#A7A8A9',
          width: 1,
          type: 'solid',
        },
      },
    },
    series,
  };
}

// 偏差功率
export function deviationPower(data = []) {
  const grid = {
    top: 28,
    left: 46,
    bottom: 45,
    right: 0,
  };
  const COLORLIST = [
    '#FA752B',
    '#5E92F6',
    '#67DCAB',
    '#078588',
    '#64779B',
    '#76D4F9',
    '#EE8CB7',
    '#F4903D',
    '#9562BF',
    '#A6D547',
    '#F5BE15',
  ];
  const XAXIS = TIME_ENUM(24);
  const yAxis = [
    {
      type: 'value',
      name: 'MW',
      axisLine: {
        show: false,
      },
      axisTick: {
        alignWithLabel: true,
        length: 4,
        lineStyle: {
          color: getCssVariableValue('--chart-y-line'),
        },
      },
      axisLabel: {
        color: getCssVariableValue('--chart-font-color'),
        fontStyle: 'DIN-Light',
        fontSize: 12,
        margin: 8,
        height: 12,
      },
      splitLine: {
        show: true,
        lineStyle: {
          type: 'solid',
          color: getCssVariableValue('--chart-y-line'),
        },
      },
    },
  ];
  const legendData = data?.map((item, index) => {
    return {
      name: item?.dataSourceName,
      itemStyle: {
        opacity: 1,
        borderWidth: 1,
        // borderColor: COLORLIST[index],
        // color: '#222629',
      },
    };
  });
  const series = data?.map((item, index) => {
    return getSeri({
      type: 'line',
      name: item?.dataSourceName,
      color: COLORLIST[index],
      data: item?.values.map((i) => (i || i === 0 ? ToFixed(i, 3) : '-')),
    });
  });
  const option = getOptions({
    titleText: '',
    XAXIS,
    grid,
    yAxis,
    dataZoom: [],
    legendData,
  });
  return {
    ...option,
    tooltip: {
      ...option.tooltip,
      formatter: (e) => formatNomalTooltip(e),
      axisPointer: {
        type: 'line',
        lineStyle: {
          color: '#A7A8A9',
          width: 1,
          type: 'solid',
        },
      },
    },
    series,
  };
}

// 预测功率
export function predictivePower(data = {}, capacity, startDate, endDate) {
  const COLORLIST = [
    '#5E92F6',
    '#67DCAB',
    '#078588',
    '#64779B',
    '#76D4F9',
    '#EE8CB7',
    '#F4903D',
    '#9562BF',
    '#A6D547',
    '#F5BE15',
  ];
  const _predictivePowerData = data?.predictivePowerData || {};
  let _maintenanceScheduleData = _.cloneDeep(data?.maintenanceScheduleData || []).filter(
    (item) => item.planState !== 1,
  );
  _maintenanceScheduleData.reverse();
  const dateObjList = _maintenanceScheduleData.map((item) => {
    let startNode =
      item.startDate && item?.startTime
        ? moment(`${item.startDate} ${item?.startTime}`).format('HHmm') === '0000'
          ? moment(`${item.startDate} ${item?.startTime}`)
              .subtract(1, 'day')
              .format('YYYYMMDD 2400')
          : moment(`${item.startDate} ${item?.startTime}`).format('YYYYMMDD HHmm')
        : '';
    let endNode =
      item.endDate && item?.endTime
        ? moment(`${item.endDate} ${item?.endTime}`).format('HHmm') === '0000'
          ? moment(`${item.endDate} ${item?.endTime}`).subtract(1, 'day').format('YYYYMMDD 2400')
          : moment(`${item.endDate} ${item?.endTime}`).format('YYYYMMDD HHmm')
        : '';
    return {
      startNode,
      endNode,
      value: item?.effectCapacity,
    };
  });
  const _startDate = startDate
    ? moment(startDate).format('YYYY-MM-DD')
    : moment().format('YYYY-MM-DD');
  const _endDate = endDate ? moment(endDate).format('YYYY-MM-DD') : moment().format('YYYY-MM-DD');
  const dateList = enumerateDaysBetweenDates(_startDate, _endDate);
  const grid = [
    {
      top: 6,
      left: 46,
      right: 0,
      height: 300,
    },
    {
      left: 46,
      right: 0,
      top: 358,
      height: 176,
    },
  ];
  let _legendData = Object.keys(_predictivePowerData).map((item, index) => {
    return {
      name: item,
      itemStyle: {
        opacity: 1,
        borderWidth: 1,
        // borderColor: COLORLIST[index] || '#222629',
        // color: '#222629',
      },
    };
  });
  _legendData = [
    {
      name: IFixedPredictivePowerLine.CAPACITY,
      itemStyle: {
        opacity: 1,
        borderWidth: 1,
        // borderColor: '#E86452',
        // color: '#222629',
      },
    },
    ..._legendData,
    {
      name: IFixedPredictivePowerLine.AFFECT_CAPACITY,
      icon: 'rect',
    },
  ];

  let XAXIS = [];
  dateList.forEach((item) => {
    const arr = Array.from(
      { length: 96 },
      (v, j) => `${moment(item).format('YYYYMMDD')} ${POINTER_NUM[j]}`,
    );
    XAXIS = [...XAXIS, ...arr];
  });
  let dataTwo = Array.from({ length: XAXIS.length }, (v, j) => undefined);
  dateObjList.forEach((i) => {
    let startIndex =
      XAXIS.findIndex((j) => j === i.startNode) === -1
        ? 0
        : XAXIS.findIndex((j) => j === i.startNode);
    let endIndex =
      XAXIS.findIndex((j) => j === i.endNode) === -1
        ? XAXIS.length - 1
        : XAXIS.findIndex((j) => j === i.endNode);
    dataTwo = dataTwo.map((x, y) => {
      if (y >= startIndex && y <= endIndex) {
        return i.value;
      } else {
        return x;
      }
    });
  });
  // 获取标线数据
  const getMarkLine = function (list) {
    const markline = [];
    list.map((item) => {
      const obj = {};
      if (item.includes('2400')) {
        obj.xAxis = item;
        markline.push(obj);
      }
    });
    return markline;
  };
  const markLine = {
    symbol: 'none',
    silent: true,
    label: { formatter: '' },
    lineStyle: { type: 'solid', color: getCssVariableValue('--chart-y-line') },
    data: XAXIS.length > 96 ? getMarkLine(XAXIS) : [],
  };
  const yAxis = [
    {
      type: 'value',
      position: 'left',
      gridIndex: 0,
      axisLine: {
        show: false,
      },
      axisTick: {
        alignWithLabel: true,
        length: 4,
        lineStyle: {
          color: getCssVariableValue('--chart-y-line'),
        },
      },
      axisLabel: {
        color: getCssVariableValue('--chart-font-color'),
        fontStyle: 'DIN-Light',
        fontSize: 12,
        margin: 8,
        height: 12,
      },
      splitLine: {
        show: true,
        lineStyle: {
          type: 'solid',
          color: getCssVariableValue('--chart-y-line'),
        },
      },
    },
    {
      type: 'value',
      position: 'left',
      gridIndex: 1,
      axisLine: {
        show: false,
      },
      axisTick: {
        alignWithLabel: true,
        length: 4,
        lineStyle: {
          color: getCssVariableValue('--chart-y-line'),
        },
      },
      axisLabel: {
        color: getCssVariableValue('--chart-font-color'),
        fontStyle: 'DIN-Light',
        fontSize: 12,
        margin: 8,
        height: 12,
      },
      splitLine: {
        show: true,
        lineStyle: {
          type: 'solid',
          color: getCssVariableValue('--chart-y-line'),
        },
      },
    },
  ];

  const xAxis = [
    {
      type: 'category',
      data: XAXIS,
      gridIndex: 0,
      axisLine: {
        show: true,
        onZero: false,
        lineStyle: {
          color: getCssVariableValue('--chart-x-line'),
        },
      },
      axisLabel: {
        color: getCssVariableValue('--chart-font-color'),
      },
      axisTick: {
        alignWithLabel: true,
      },
    },
    {
      type: 'category',
      gridIndex: 1,
      data: XAXIS,
      axisLine: {
        lineStyle: {
          color: getCssVariableValue('--chart-x-line'),
        },
      },
      axisLabel: {
        show: false,
      },
      axisTick: {
        show: false,
      },
    },
  ];

  const axisPointer = {
    link: [
      {
        xAxisIndex: 'all',
      },
    ],
    lineStyle: {
      color: 'rgba(24, 160, 251, 0.5)',
      type: 'solid',
    },
  };
  const toolbox = {
    show: false,
  };

  const series = _legendData.map((item, index) => {
    let _series;
    if (item.name === IFixedPredictivePowerLine.CAPACITY) {
      _series = getSeri({
        name: IFixedPredictivePowerLine.CAPACITY,
        type: 'line',
        color: '#E86452',
        xAxisIndex: 0,
        yAxisIndex: 0,
        data: Array.from({ length: XAXIS?.length ?? 0 }, (v, j) => ToFixed(capacity)),
      });
    } else if (item.name === IFixedPredictivePowerLine.AFFECT_CAPACITY) {
      _series = getSeri({
        name: IFixedPredictivePowerLine.AFFECT_CAPACITY,
        type: 'line',
        color: 'rgba(253, 79, 67, 0.2)',
        data: dataTwo.map((item) => {
          if (item) {
            let a = ToFixed(item, 3);
            return a;
          } else {
            return '-';
          }
        }),
        xAxisIndex: 1,
        yAxisIndex: 1,
        markLine: markLine,
        symbol: 'none',
        areaStyle: {},
        lineStyle: { width: 0, color: '#222629' },
      });
    } else {
      let _data = [];
      dateList.forEach((day) => {
        if (_predictivePowerData[item.name][day]) {
          _data = [..._data, ..._predictivePowerData[item.name][day]];
        } else {
          let arr = Array.from({ length: 96 }, (v, j) => undefined);
          _data = [..._data, ...arr];
        }
      });
      _series = getSeri({
        name: item.name,
        type: 'line',
        markLine: markLine,
        xAxisIndex: 0,
        yAxisIndex: 0,
        color: COLORLIST[index - 1] || '#222629',
        data: _data.map((i) => ToFixed(i)),
      });
    }
    return _series;
  });

  const option = getOptions({
    grid,
    xAxis,
    yAxis,
    dataZoom: [],
    toolbox,
    legendData: _legendData,
  });

  return {
    ...option,
    axisPointer,
    tooltip: {
      ...option.tooltip,
      formatter: (e) => formatSpecialTooltipTwo(e),
      axisPointer: {
        type: 'line',
        lineStyle: {
          color: 'rgba(24, 160, 251, 0.5)',
          width: 1,
          type: 'solid',
        },
      },
    },
    series: series,
  };
}

// 全部检修计划
export function yearlyMaintenancePlans(data, startDate) {
  let _data = data ? Object.entries(data) : [];
  _data = _data.map((item) => {
    return [item[0], item[1] ? item[1] : undefined];
  });
  const _max = _.max(Object.values(data));
  const year = startDate ? moment(startDate).format('YYYY') : moment().format('YYYY');
  const option = {
    visualMap: {
      min: 0,
      max: _max ?? 0,
      show: false,
    },
    gradientColor: [
      '#4C010C',
      '#6E111D',
      '#92232C',
      '#B8343B',
      '#DF474A',
      '#F76965',
      '#F98784',
      '#FAA5A3',
      '#FCC3C1',
      '#FDE1E0',
    ],
    darkMode: true,
    // backgroundColor: '#222629',
    textStyle: {
      color: getCssVariableValue('--font'),
      fontSize: 12,
    },
    calendar: {
      range: year,
      left: 28,
      top: 28,
      right: 0,
      bottom: 0,
      yearLabel: { show: false },
      monthLabel: {
        color: getCssVariableValue('--chart-font-color'),
        nameMap: [
          '1月',
          '2月',
          '3月',
          '4月',
          '5月',
          '6月',
          '7月',
          '8月',
          '9月',
          '10月',
          '11月',
          '12月',
        ],
        show: true,
      },
      dayLabel: {
        color: getCssVariableValue('--chart-font-color'),
        nameMap: ['日', '一', '二', '三', '四', '五', '六'],
        show: true,
      },
      splitLine: {
        lineStyle: {
          color: getCssVariableValue('--chart-font-color'),
        },
      },
      itemStyle: {
        color: getCssVariableValue('--bd-a20'),
        borderWidth: 1,
        borderColor: getCssVariableValue('--bg-main'),
      },
      select: {
        itemStyle: {
          borderColor: '#4E5154',
        },
      },
    },
    series: {
      type: 'heatmap',
      coordinateSystem: 'calendar',
      data: _data,
    },
  };
  return option;
}
